#include "singleapplication.h"
#include "definitions.h"
#include <QtDebug>

#ifndef HAVE_DBUS
#include <QMessageBox>
#else
#include <QtDBus>
#endif


SingleApplication::SingleApplication(int &argc, char *argv[], const QString uniqueKey) : QApplication(argc, argv),
      _isRunning(false),
      _uniqueKey(uniqueKey) {

#ifndef QT_NO_SHAREDMEMORY
    sharedMemory.setKey(_uniqueKey);

    if (sharedMemory.attach()) {
        _isRunning = true;
#ifdef HAVE_DBUS
		qDebug() << QString("%1 Another instance is running already. Notifying it.").arg(APP_ID);
        QDBusInterface dbus(DBUS_SERVICE, DBUS_PATH, DBUS_INTERFACE, QDBusConnection::sessionBus());
        if (!dbus.isValid()) {
			qWarning() << QString("%1 DbusCall: QDBusInterface is invalid").arg(APP_ID);
            return;
        }
        QDBusMessage msg = dbus.call("raise");
        if (!msg.errorName().isEmpty())
			qDebug() << QString("%1 %2").arg(APP_ID, msg.errorMessage());
#else
		QMessageBox::warning(0, tr("RSSGuard is running already"),
                             tr("Another instance of RSSGuard is already running."));
#endif

    }
    else {
        _isRunning = false;
		// Create shared memory.
        if (!sharedMemory.create(1)) {
			qDebug() << QString("%1 Unable to create single instance.").arg(APP_ID);
            return;
        }
    }
#else
	qDebug() << QString("%1 QT_NO_SHAREDMEMORY is defined. There can run more instances of RSSGuard. Sorry. (OS/2)").arg(APP_ID);
#endif
}

SingleApplication::~SingleApplication() {
#ifndef QT_NO_SHAREDMEMORY
    bool res = sharedMemory.detach();
    qDebug() << QString("%1 Detaching from shared memory.").arg(APP_ID);
#endif
}

bool SingleApplication::isRunning() {
    return _isRunning;
}
